<?php

namespace app\api\controller\group;

use app\api\BaseController;
use app\api\service\ResellService;
use app\store\service\GroupActivityService;
use think\facade\Db;
use WeChat\Contracts\Tools;

class TradeController extends BaseController
{
    /**
     * 微信回调
     * */
    public function wxFinishNotify()
    {
        $result = Tools::xml2arr(file_get_contents('php://input'));
        if (!empty($result)) {
            if ($result['return_code'] == 'SUCCESS' && $result['result_code'] == 'SUCCESS') {
                $groupOrder = Db::name('group_order_trade')
                    ->alias('a')
                    ->field('a.group_order_id,b.user_id,b.prepayment_amount,a.trade_fee')
                    ->join('group_order b', 'a.group_order_id=b.id')
                    ->where('a.out_trade_no', $result['out_trade_no'])
                    ->find();

                Db::name('group_order_trade')
                    ->where('out_trade_no', $result['out_trade_no'])
                    ->update([
                        'trade_status' => 1,
                        'trade_time' => strtotime($result['time_end']),
                    ]);

                $real_amount = number_format($groupOrder['prepayment_amount'] + $groupOrder['trade_fee'], 2);

                Db::name('group_order')->where('group_order_id', $groupOrder['group_order_id'])->update([
                    'real_amount' => $real_amount,
                    'status' => 3,
                ]);

                $goods = ResellService::findGroupActivityGoods($groupOrder['group_order_id']);

                ResellService::receiveGroupGoods($groupOrder['user_id'], $goods);

                echo '<xml>' .
                    '<return_code><![CDATA[SUCCESS]]></return_code>' .
                    '<return_msg><![CDATA[OK]]></return_msg>' .
                    '</xml>';
                exit();
            }
        }

    }

    /**
     * 支付宝回调
     * */
    public function aliFinishNotify()
    {
        $post = $_POST;
        if (!empty($post)) {
            if ($post['trade_status'] == 'TRADE_SUCCESS') {
                $groupOrder = Db::name('group_order_trade')
                    ->alias('a')
                    ->field('a.group_order_id,b.user_id,b.prepayment_amount,a.trade_fee')
                    ->join('group_order b', 'a.group_order_id=b.id')
                    ->where('a.out_trade_no', $post['out_trade_no'])
                    ->find();

                Db::name('group_order_trade')
                    ->where('out_trade_no', $post['out_trade_no'])
                    ->update([
                        'trade_status' => 1,
                        'trade_time' => strtotime($post['gmt_payment']),
                    ]);

                $real_amount = number_format($groupOrder['prepayment_amount'] + $groupOrder['trade_fee'], 2);

                Db::name('group_order')->where('group_order_id', $groupOrder['group_order_id'])->update([
                    'real_amount' => $real_amount,
                    'status' => 3,
                ]);

                $goods = ResellService::findGroupActivityGoods($groupOrder['group_order_id']);

                ResellService::receiveGroupGoods($groupOrder['user_id'], $goods);

                echo 'success';
            }
        }
    }

    /**
     * 微信回调
     * */
    public function wxNotify()
    {
        $result = Tools::xml2arr(file_get_contents('php://input'));
        if (!empty($result)) {
            if ($result['return_code'] == 'SUCCESS' && $result['result_code'] == 'SUCCESS') {
                $this->changeTrade($result['out_trade_no'], $result['time_end']);
                echo '<xml>' .
                    '<return_code><![CDATA[SUCCESS]]></return_code>' .
                    '<return_msg><![CDATA[OK]]></return_msg>' .
                    '</xml>';
                exit();
            }
        }

    }
    /**
     * 支付宝回调
     * */
    public function aliNotify()
    {
        $post = $_POST;
        if (!empty($post)) {
            if ($post['trade_status'] == 'TRADE_SUCCESS') {
                $this->changeTrade($post['out_trade_no'], $post['gmt_payment']);
                echo 'success';
            }
        }
    }

    public function changeTrade($out_trade_no, $time_end)
    {
        $groupOrder = Db::name('group_order_trade')
            ->alias('a')
            ->field('a.group_order_id,b.prepayment_amount,a.trade_fee')
            ->join('group_order b', 'a.group_order_id=b.id')
            ->where('a.out_trade_no', $out_trade_no)
            ->find();

        Db::name('group_order_trade')
            ->where('out_trade_no', $out_trade_no)
            ->update([
                'trade_status' => 1,
                'trade_time' => strtotime($time_end),
            ]);

        $status = 3;
        $group_order_id = $groupOrder['group_order_id'];
        if ($groupOrder['prepayment_amount'] > 0) {
            $status = 2;
        }

        Db::name('group_order')->where('id', $group_order_id)->update([
            'status' => $status,
        ]);

        if ($status == 3 && $groupOrder['logistics_mode'] == 2) {
            Db::name('group_order')->where('id', $group_order_id)->update([
                'status' => 4, 'ship_time' => time(),
            ]);
        }

        $group_activity = Db::name('group_activity_record')
            ->alias('a')
            ->field('b.id,b.store_id,a.group_num,b.end_time,b.success_rule,b.fail_rule')
            ->join('group_activity b', 'a.group_activity_id=b.id')
            ->withAttr('success_rule', function ($value) {
                return json_decode($value, true);
            })->withAttr('fail_rule', function ($value) {
            return json_decode($value, true);
        })->where('a.group_order_id', $group_order_id)
            ->where('b.status', 1)
            ->find();

        if (!empty($group_activity) && $group_activity['group_num'] != -1) {
            $group_num = Db::name('group_activity_record')
                ->alias('a')
                ->join('group_order_trade b', 'a.group_order_id=b.group_order_id')
                ->where([
                    'a.group_activity_id' => $group_activity['id'],
                    'b.trade_status' => 1,
                ])->count('a.id');
            if ($group_num == $group_activity['group_num']) {
                $records = GroupActivityService::getActivityRecord($group_activity['id']);
                $data = GroupActivityService::finishGroupActivity($group_activity, $records);
                if (!empty($data)) {
                    GroupActivityService::saveSuccessAwardQueue($data['user_id'], $data['success_gift']);
                    GroupActivityService::saveFailAwardQueue($data['user_ids'], $data['fail_gift']);
                    GroupActivityService::saveFailRefundQueue($data['store_id'], $data['group_orders']);
                }
            }
        }

    }

}
